package Runde8;

public abstract class TwoWayWorker extends OneWayWorker {

	private final Storage source;
	private final int toGet;
	
	/**
	 * @precondition None of the arguments may be empty (null).
	 * @postcondition Creates a worker.
	 */
	public TwoWayWorker(Storage source, Storage target, int wTime, int toGet, int toGive, Company comp) {
		super(target, wTime, toGive, comp);
		this.source = source;
		this.toGet = toGet;
	}
	
	/**
	 * @postcondition Executed when Thread is started, work is done until comp's operation is stopeed or source has no
	 * 					activeMembers more and is empty
	 */
	public void run() {
		while (super.comp.inOperation() && (source.hasActiveWorkers() || !source.isEmpty())) {
			work();
		}
		super.target.signOff();
	}
	
	/**
	 * @postcondition Waits until there are enough goods in the source storage, takes them and calls super.work().
	 */
	protected void work() {
		try {
			synchronized(source) {
				while(!source.tryGet(toGet)){
						source.wait();
				}
			}
			super.work();
		} catch (InterruptedException e) {}
			
	}
}





